#import "FlutterAtauthPlugin.h"
#import <ATAuthSDK/ATAuthSDK.h>

#define TX_SCREEN_WIDTH                    [[UIScreen mainScreen] bounds].size.width
#define TX_SCREEN_HEIGHT                   [[UIScreen mainScreen] bounds].size.height

@interface FlutterAtauthPlugin ()

@property(copy, nonatomic) FlutterResult result;
@property (nonatomic, assign) BOOL isEnable;
@property (nonatomic, assign) CGFloat ratio;
@property (assign, nonatomic) double time;

@end

@implementation FlutterAtauthPlugin {
  UIViewController *_viewController;
  FlutterBasicMessageChannel *_channel;
}

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"flutter_atauth"
            binaryMessenger:[registrar messenger]];
  UIViewController *viewController =
      [UIApplication sharedApplication].delegate.window.rootViewController;
  FlutterAtauthPlugin* instance = [[FlutterAtauthPlugin alloc] initWithViewController:viewController registrar:registrar];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (instancetype)initWithViewController:(UIViewController *)viewController registrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  self = [super init];
  if (self) {
    _viewController = viewController;
      _channel = [FlutterBasicMessageChannel messageChannelWithName:@"flutter_atauth_platform" binaryMessenger:[registrar messenger] codec: [FlutterStringCodec sharedInstance]];
  }
  self.ratio = TX_SCREEN_HEIGHT / 667.0;
  self.time = 80000;
  return self;
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getLoginToken" isEqualToString:call.method]) {
    @try 
    {
        NSString *appKey = call.arguments[@"appKey"];
        [self getLoginMobileAndToken:appKey];
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    }
    @catch (NSException *exception) {
        NSString *ret = @"{\"msg\": \"SDK出错\"}";
        [self receivedResult:ret];
    }
    @finally 
    {

    }
  } else {
    result(FlutterMethodNotImplemented);
  }
}

- (void)receivedResult: (NSString *)ret {
    [_channel sendMessage:ret];
}

- (TXCustomModel*) customModel {
    UIColor *backgroundColor = UIColor.blackColor;
    UIColor *navBackColor = [UIColor colorWithRed:15.0/255.0 green:15.0/255.0 blue:18.0/255.0 alpha:1.0];
    UIColor *primaryColor = [UIColor colorWithRed:102.0/255.0 green:95.0/255.0 blue:1.0 alpha:1.0];
    UIColor *titleColor = UIColor.whiteColor;
    UIColor *descColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.5];
    // 授权页面属性定制
    TXCustomModel *modelNew = [[TXCustomModel alloc] init];
    modelNew.navColor = navBackColor;
    modelNew.navTitle = [[NSAttributedString alloc] initWithString:@"一键登录" attributes:@{NSForegroundColorAttributeName : titleColor,NSFontAttributeName : [UIFont systemFontOfSize:17.0]}];
//    modelNew.navBackImage = [UIImage imageNamed:@"icon_nav_back_gray"];
    modelNew.hideNavBackItem = YES;
    modelNew.checkBoxIsHidden = YES;
    
    modelNew.numberColor = primaryColor;
    modelNew.changeBtnTitle = [[NSAttributedString alloc] initWithString:@"切换到其它方式" attributes:@{NSForegroundColorAttributeName : primaryColor,NSFontAttributeName : [UIFont systemFontOfSize:13.0]}];
    modelNew.customViewBlock = ^(UIView * _Nonnull superCustomView) {
        superCustomView.backgroundColor = backgroundColor;
    };

    modelNew.privacyColors = [NSArray arrayWithObjects:descColor,primaryColor,nil];
    return modelNew;
}

- (void) oneLogin {
    __weak UIViewController *weakSelf = _viewController;
    TXCustomModel* modelNew = [self customModel];
    
    [[TXCommonHandler sharedInstance] getLoginTokenWithTimeout: self.time controller: _viewController model:modelNew complete:^(NSDictionary * _Nonnull resultDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *code = [resultDic valueForKey:@"resultCode"];
             if ([code isEqualToString:PNSCodeSuccess]) {//成功登录
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
                NSString *token = [resultDic valueForKey:@"token"];
                // 可以去请求服务端getMobile接口，用token换取手机号码啦
#ifdef DEBUG
                NSLog(@"getLoginTokenWithController,token = %@", token);
#endif
            }
            else if (
                     [code isEqualToString:PNSCodeLoginControllerClickChangeBtn] || //切换到其他方式
                     [code isEqualToString:PNSCodeLoginControllerClickCancel]
            ) {
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }
            else if (
                     [PNSCodeLoginControllerPresentSuccess isEqualToString:code] ||
                     [PNSCodeLoginControllerClickProtocol isEqualToString:code] ||
                     [PNSCodeLoginControllerClickCheckBoxBtn isEqualToString:code] ||
                     [PNSCodeLoginControllerClickLoginBtn isEqualToString:code]
            ) {
                
            }
            else {
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
                NSLog(@"getLoginTokenWithController fail,resultDic = %@",resultDic);
            }
            NSString *ret = [self jsonStrFromDic:resultDic];
            [self receivedResult:ret];
#ifdef DEBUG
            NSLog(@"getLoginTokenWithController,resultDic = %@",ret);
#endif
        });
    }];
}

- (void)getLoginMobileAndToken:(NSString*) appKey {
    [[TXCommonHandler sharedInstance] setAuthSDKInfo:appKey complete:^(NSDictionary * _Nonnull resultDic) {
        
    }];
    [[TXCommonHandler sharedInstance] checkEnvAvailableWithComplete:^(NSDictionary * _Nonnull resultDic) {
         dispatch_async(dispatch_get_main_queue(), ^{
             NSString *code = [resultDic valueForKey:@"resultCode"];
             if ([code isEqualToString:@"600000"]) {
                 [self oneLogin];
             } else {
                 NSString *ret = [self jsonStrFromDic:resultDic];
                 [self receivedResult:ret];
             }
         });
    }];
}


-(NSString *)jsonStrFromDic:(NSDictionary *)dic {
    
    if (dic == nil)
    {
        return nil;
    }
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&parseError];
    if(parseError)
    {
        NSString *errorString = [NSString stringWithFormat:@"字典转json失败____%@",parseError.description];
        NSLog(@"jsonStrFromDic error，errorString = %@",errorString);
        return nil;
    }
    NSString * str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return str;
}

@end
